package com.cloud.service.wxusersubscribe.impl;

import com.cloud.commons.constants.ConsumeConstant;
import com.cloud.dao.wxusersubscribe.WxUserSubscribeDao;
import com.cloud.model.entity.wxusersubscribe.WxUserSubscribe;
import com.cloud.model.view.wxusersubscribe.WxUserSubscribeView;
import com.cloud.service.wxusersubscribe.WxUserSubscribeService;
import com.cloud.commons.utils.CloudCopyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
* <b><code>WxUserSubscribeImpl</code></b>
* <p/>
* WxUserSubscribe的具体实现
* <p/>
* <b>Creation Time:</b> 2020-01-12 00:22:03.
*
* @author ${model.author}
* @version 1.0.0
* @since cloud-spring-boot-be 1.0.0
*/
@Service
public class WxUserSubscribeServiceImpl implements WxUserSubscribeService {

    /**
     * The Constant LOG.
     */
    private static final Logger LOG = LoggerFactory
            .getLogger(WxUserSubscribeServiceImpl.class);

    @Autowired
    private WxUserSubscribeDao wxUserSubscribeDao;

    @Override
    public WxUserSubscribeView getEntity(long id) {
        // 获取Entity
        WxUserSubscribe wxUserSubscribe = wxUserSubscribeDao.getOne(id);
        // 复制Dao层属性到view属性
        WxUserSubscribeView wxUserSubscribeView = new WxUserSubscribeView();
        CloudCopyUtils.copyBean(wxUserSubscribe, wxUserSubscribeView);
        return wxUserSubscribeView;
    }

    @Override
    public long getEntitiesCount() {
        return wxUserSubscribeDao.count();
    }

    @Override
    public List<WxUserSubscribeView> findAll() {
        List<WxUserSubscribeView> wxUserSubscribeViews = new ArrayList<>();
        List<WxUserSubscribe> wxUserSubscribes = wxUserSubscribeDao.findAll();
        for (WxUserSubscribe wxUserSubscribe : wxUserSubscribes){
            WxUserSubscribeView wxUserSubscribeView = new WxUserSubscribeView();
            CloudCopyUtils.copyBean(wxUserSubscribe, wxUserSubscribeView);
            wxUserSubscribeViews.add(wxUserSubscribeView);
        }
        return wxUserSubscribeViews;
    }

    @Override
    public WxUserSubscribeView saveEntity(WxUserSubscribeView wxUserSubscribeView)  {
        if (ObjectUtils.isEmpty(wxUserSubscribeView.getSubscribeId()) || ObjectUtils.isEmpty(wxUserSubscribeView.getUserId())) {
            throw new RuntimeException("缺少参数信息,无法进行保存");
        }
        // 保存的业务逻辑
        WxUserSubscribe wxUserSubscribe = wxUserSubscribeDao.findByUserIdAndSubscribeId(wxUserSubscribeView.getUserId(),wxUserSubscribeView.getSubscribeId());
        if (ObjectUtils.isEmpty(wxUserSubscribe)) {
            wxUserSubscribe = new WxUserSubscribe();
            wxUserSubscribe.setCreateTime(System.currentTimeMillis());
            wxUserSubscribe.setEnabled(ConsumeConstant.ENABLED);
        }
        CloudCopyUtils.copyBeanExcludeNull(wxUserSubscribeView, wxUserSubscribe);
        // user数据库映射传给dao进行存储
        wxUserSubscribe.setUpdateTime(System.currentTimeMillis());
        wxUserSubscribe.setWeight(System.currentTimeMillis());
        wxUserSubscribeDao.save(wxUserSubscribe);
        CloudCopyUtils.copyBean(wxUserSubscribe,wxUserSubscribeView);
        return wxUserSubscribeView;
    }

    @Override
    public void deleteEntity(long id) {
        WxUserSubscribe wxUserSubscribe = new WxUserSubscribe();
        wxUserSubscribe.setId(id);
        wxUserSubscribeDao.delete(wxUserSubscribe);
    }

    @Override
    @Transactional(rollbackOn = { Exception.class })
    public void deleteEntities(String ids) {
        String[] entityIds= ids.split("\\,");
        List<WxUserSubscribe> wxUserSubscribes = new ArrayList<>();
        for(String entityId : entityIds){
            WxUserSubscribe wxUserSubscribe = new WxUserSubscribe();
            wxUserSubscribe.setId(Long.valueOf(entityId));
            wxUserSubscribes.add(wxUserSubscribe);
        }
        wxUserSubscribeDao.deleteInBatch(wxUserSubscribes);
    }

    @Override
    public void updateEntity(WxUserSubscribeView wxUserSubscribeView) {
        Specification<WxUserSubscribe> wxUserSubscribeSpecification = Optional.ofNullable(wxUserSubscribeView).map( s -> {
            return new Specification<WxUserSubscribe>() {
                @Override
                public Predicate toPredicate(Root<WxUserSubscribe> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                    List<Predicate> predicates = new ArrayList<>();
                    // id
                    predicates.add(criteriaBuilder.equal(root.get("id").as(Long.class), s.getId()));

                    criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
                    return criteriaQuery.getRestriction();
                }
            };
        }).orElseThrow(()->new IllegalArgumentException("WxUserSubscribeView is null"));


        // 获取原有的属性，把不变的属性覆盖
        Optional<WxUserSubscribe> wxUserSubscribeOptionalBySearch = wxUserSubscribeDao.findOne(wxUserSubscribeSpecification);
        wxUserSubscribeOptionalBySearch.map(wxUserSubscribeBySearch -> {
            CloudCopyUtils.copyBeanExcludeNull(wxUserSubscribeView,wxUserSubscribeBySearch);
            wxUserSubscribeBySearch.setUpdateTime(System.currentTimeMillis());
            wxUserSubscribeDao.save(wxUserSubscribeBySearch);
            return "";
        }).orElseThrow(()->new RuntimeException("无法找到id为" + wxUserSubscribeView.getId() + "的数据记录"));
    }
}
